<template>
	<view class="pay-order">
		<view class="block">
			<view class="money">
				<span class="unit">¥</span>
				<span class="number">{{dataObj.amount}}</span>
			</view>
			<view class="text">合计支付</view>
		</view>
		<view class="block no-p-b">
			<view class="title">支付方式</view>
			<view class="list">
				<view class="item" v-for="(item, idx) in pageObj.payList" :key="item.type" @click="onSelectTap(idx)">
					<view class="icon" :class="item.type"></view>
					<view class="name">{{item.title}}</view>
					<view class="select" :class="pageObj.selectIndex === idx ? 'selected' : ''"></view>
				</view>
			</view>
		</view>
		<view class="footer">
			<view class="btn" @click="onPayTap">确认支付</view>
		</view>
	</view>
</template>

<script>
	import { requestErrorTip } from '@/common/tools.js';
	
	export default {
		data() {
			return {
				pageObj: {
					selectIndex: 0,
					payList: [],
					tradeType: {}
				},
				dataObj: {
					coupon_code: '', // 优惠券码
					payment_type: '', // 订单类型
					ids: '', // 购物车id
					ship_id: '', // 地址id
					money: '', // 充值金额
					amount: '0.00' // 支付金额
				}
			}
		},
		onLoad(event) {
			this.dataObj['payment_type'] = event['payment_type']; // 获取订单类型
			this.dataObj['ids'] = event['ids']; // 获取购物车id
			this.dataObj['ship_id'] = event['ship_id'] || ''; // 获取地址id
			this.dataObj['money'] = event['money']; // 获取充值金额
			this.dataObj['amount'] = event['amount']; // 获取支付金额
			this.dataObj['coupon_code'] = event['coupon_code']; // 优惠券码
			
			this.initPayWay();
			if(this.dataObj['ids']) {
				// 消费
				this.postCreateOrder();
			} else if (this.dataObj['money']) {
				// 充值
				this.postCreateChargeOrder();
			} else {
				// 订单列表进来
				this.dataObj['order_id'] = event['order_id'];
			}
			// 1.微信支付：1.trade_type默认是JSAPI：移动端类型(小程序：JSAPI， H5端：MWEB， app端: APP) 。
			// 2.支付宝支付：1.trade_type默认是WAP ：移动端类型(小网页：PC， H5端：WAP， app端: APP)
			
			
			//  App 平台支付判断
			// #ifdef APP-PLUS
			this.pageObj['tradeType'] = {
				wechatpay: 'APP',
				alipay: 'APP'
			}
			// #endif
			
			//  微信小程序支付判断
			// #ifdef MP-WEIXIN
			this.pageObj['tradeType'] = {
				wechatpay: 'JSAPI',
			}
			// #endif
			
			// H5 支付判断
			// #ifdef H5
			let ua = window.navigator.userAgent.toLowerCase()
			console.log(ua.match(/MicroMessenger/i), 'H5')
			if (ua.match(/MicroMessenger/i) == 'micromessenger') {
				// 微信浏览器
				this.pageObj['tradeType'] = {
					wechatpay: 'JSAPI_OFFICIAL'
				}
			} else {
				// 非微信浏览器
				this.pageObj['tradeType'] = {
					wechatpay: 'MWEB',
					alipay: 'WAP'
				}
			}
			// #endif

		},
		methods: {
			// 初始化支付方式
			initPayWay() {
				let list = [];
				// 微信小程序 支付判断
				// #ifdef MP-WEIXIN
				list = [{
					title: '微信支付',
					type: 'wechatpay'
				}];
				// #endif
				
				// H5 支付判断
				// #ifdef H5
				// let ua = window.navigator.userAgent.toLowerCase()
				// if (ua.match(/MicroMessenger/i) == 'micromessenger') {
				let isWeiXin = this.isWeiXinBrowser()
				if (isWeiXin) {
					// 微信服务器
					list = [{
						title: '微信支付',
						type: 'wechatpay'
					}];
				} else {
					list = [{
						title: '微信支付',
						type: 'wechatpay'
					}, {
						title: '支付宝支付',
						type: 'alipay'
					}];
				}
				// #endif
				
				// APP 支付判断
				// #ifdef APP-PLUS
				list = [{
					title: '微信支付',
					type: 'wechatpay'
				}, {
					title: '支付宝支付',
					type: 'alipay'
				}];
				// #endif
				
				this.pageObj['payList'] = list;
			},
			onSelectTap(index) {
				this.pageObj['selectIndex'] = index;
			},
			isWeiXinBrowser() {
				// #ifdef H5
				// window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
				let ua = window.navigator.userAgent.toLowerCase()
				// 通过正则表达式匹配ua中是否含有MicroMessenger字符串
				if (ua.match(/MicroMessenger/i) == 'micromessenger') {
					return true
				} else {
					return false
				}
				// #endif

				return false
			},
			// 支付
			onPayTap() {
				const that = this;
				const index = this.pageObj['selectIndex'];
				const payment_code = this.pageObj['payList'][index]['type'];
				// H5 支付判断，非微信浏览器
				// #ifdef H5
				let isWeiXin = this.isWeiXinBrowser()
				if (isWeiXin) {
					// 微信浏览器
					const url = window.location.origin + '/wap/pages/order/auth?type=' + this.dataObj['payment_type'] + '&order_id=' + this.dataObj['order_id'];
					this.dataObj['return_url'] = url;
				} else {
					// 非微信浏览器
					const url = window.location.origin + '/wap/pages/order/pay-success?payment_type=' + this.dataObj['payment_type'] + '&order_id=' + this.dataObj['order_id'];
					this.dataObj['return_url'] = url;
				}
				// #endif
				// return false
				console.log(this.pageObj['tradeType'][payment_code], '支付支付');
				let params = {
					trade_type: this.pageObj['tradeType'][payment_code],
					return_url: this.dataObj['return_url'],
					url: this.dataObj['return_url'],
					money: this.dataObj['amount']
				};
				this.$Requset({
					url: this.$Api['pay']['wechatPay'],
					data: {
						payment_code: payment_code,
						payment_type: this.dataObj['payment_type'], // 1: 消费；2: 充值
						ids: this.dataObj['order_id'],
						coupon_code: this.dataObj['coupon_code'],
						params: JSON.stringify(params)
					},
					success: (res) => {
						const { data, status, msg } = res;
						// requestErrorTip('model', JSON.stringify(res) + 1);
						if (!status && data != 10066) {
							requestErrorTip('toast', msg);
							return;
						}
						//  微信小程序
						// #ifdef MP-WEIXIN
						this.payWechatMoney(data);
						// #endif
						
						//  App 平台支付判断
						// #ifdef APP-PLUS
						let provider = ''; // 支付类型
						let pdata = ''; // 支付数据
						if(payment_code === 'alipay') {
							// 支付宝
							provider = "alipay";
							pdata = data.data;
						} else if(payment_code === 'wechatpay') {
							// 微信
							provider = "wxpay";
							pdata = data;
						}
						// 调用支付
						uni.requestPayment({
							provider: provider,
							orderInfo: pdata,
							success: function(data) {
								// 支付成功后跳转
								that.jumpPage();
								// requestErrorTip('model', '支付成功', () => {
								// 	// 支付成功后跳转
								// 	this.jumpPage();
								// });
							},
							fail: (res) => {
								// requestErrorTip('model', JSON.stringify(res) + 'fail');
							}
						});
						// #endif
						
						//  H5
						// #ifdef H5
						let isWeiXin = this.isWeiXinBrowser()
						if(payment_code === 'alipay') {
							// 支付宝
							this.payAliMoney(data)
						} else if(payment_code === 'wechatpay') {
							// 微信
							// let ua = window.navigator.userAgent.toLowerCase()
							// if (ua.match(/MicroMessenger/i) == 'micromessenger') {
							if (isWeiXin) {
								// requestErrorTip('model', JSON.stringify(res) + 'isWeiXin：' +isWeiXin);
								// 微信浏览器
								if (!status && data === 10066) {
									window.location.href = msg
									return;
								}
								// 微信桥联
								// requestErrorTip('model', JSON.stringify(data), '1');
								this.checkWXJSBridge(data)
							} else {
								// 非微信服务器
								window.location.href = res.data.mweb_url;
							}
						}
						// #endif
					},
					fail: (err) => {
						console.log(err);
					}
				})
			},
			checkWXJSBridge(data) {
				let that = this
				let interval = setInterval(() => {
					if (typeof window.WeixinJSBridge != 'undefined') {
						clearTimeout(interval)
						that.onBridgeReady(data)
					}
				}, 200)
			},
			onBridgeReady(data) {
				// requestErrorTip('model', JSON.stringify(data), '2');
				let that = this
				window.WeixinJSBridge.invoke(
					'getBrandWCPayRequest', {
						appId: data.appid, // 公众号名称，由商户传入
						timeStamp: data.timeStamp, // 时间戳，自1970年以来的秒数
						nonceStr: data.nonceStr, // 随机串
						package: data.package,
						signType: data.signType, // 微信签名方式：
						paySign: data.paySign // 微信签名
					},
					function(res) {
						// requestErrorTip('model', JSON.stringify(res), '3');
						if (res.err_msg === 'get_brand_wcpay_request:ok') {
							requestErrorTip('toast', '支付成功');
						} else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
							requestErrorTip('toast', '取消支付');
						} else {
							requestErrorTip('toast', '支付失败');
						}
						setTimeout(() => {
							that.jumpPage();
						}, 1000)
					}
				)
			},
			// 支付宝支付
			payAliMoney(data) {
				let tempForm = document.createElement('form')
				tempForm.id = 'aliPay'
				tempForm.methods = 'post'
				tempForm.action = data['url']
				tempForm.target = '_self'
				let input = []
				for (let k in data['data']) {
					input[k] = document.createElement('input')
					input[k].type = 'hidden'
					input[k].name = k
					input[k].value = data['data'][k]
					tempForm.appendChild(input[k])
				}
				tempForm.addEventListener('submit', function() {}, false)
				document.body.appendChild(tempForm)
				tempForm.dispatchEvent(new Event('submit'))
				tempForm.submit()
				document.body.removeChild(tempForm)
			},
			// 微信支付
			payWechatMoney(params) {
				// 调起微信支付
				wx.requestPayment({
					timeStamp: params['timeStamp'],
					nonceStr: params['nonceStr'],
					package: params['package'],
					signType: params['signType'],
					paySign: params['paySign'],
					success: (res) => {
						uni.showToast({
							title: '支付成功',
							icon: 'none'
						});
						// 支付成功后跳转
						this.jumpPage();
					},
					fail: (res) => {
						uni.showToast({
							title: '支付失败，请重新支付',
							icon: 'none'
						});
					}
				});
			},
			// 成功跳转
			jumpPage() {
				uni.navigateTo({
					url: './pay-success?payment_type=' + this.dataObj['payment_type'] + '&order_id=' + this.dataObj['order_id']
				});
			},
			// 创建订单（消费）
			postCreateOrder() {
				let pData = {
					cart_ids: this.dataObj['ids'],
					coupon_code: this.dataObj['coupon_code']
				};
				if (this.dataObj['ship_id']) {
					pData['ship_id'] = this.dataObj['ship_id'];
				}
				this.$Requset({
					url: this.$Api['order']['create'],
					data: pData,
					success: (res) => {
						const { data, status, msg } = res;
						if (!status) {
							requestErrorTip('toast', msg);
							return;
						}
						this.dataObj['amount'] = data['order_amount'] || '0.00';
						this.dataObj['order_id'] = data['order_id'];
					},
					fail: (err) => {
						console.log(err);
					}
				})
			},
			// 创建订单（充值）
			postCreateChargeOrder() {
				this.$Requset({
					url: this.$Api['order']['createcharge'],
					data: {
						recharge_val: this.dataObj['money']
					},
					success: (res) => {
						const { data, status } = res;
						if (!status) {
							requestErrorTip('toast', msg);
							return;
						}
						this.dataObj['amount'] = data['order_amount'] || '0.00';
						this.dataObj['order_id'] = data['order_id'];
					},
					fail: (err) => {
						console.log(err);
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	page{
		background-color: #f5f5f5;
	}
	.pay-order{
		padding-top: 18rpx;
		.block{
			.money{
				height: 76rpx;
				line-height: 76rpx;
				color: $color-common;
				text-align: center;
				padding-top: 18rpx;
				.unit{
					font-size: 32rpx;
					margin-right: 8rpx;
				}
				.number{
					font-size: 56rpx;
					font-weight: bold;
				}
			}
			.text{
				line-height: 36rpx;
				font-size: 24rpx;
				color: #1A1A1A;
				text-align: center;
			}
			.title{
				line-height: 46rpx;
				font-size: 32rpx;
				color: #1A1A1A;
			}
			.list{
				.item{
					position: relative;
					padding: 36rpx 50rpx 36rpx 58rpx;
					border-bottom: 1rpx solid #EAEFF1;
					&:nth-last-child(1) {
						border-bottom: none;
					}
					.icon{
						position: absolute;
						top: 50%;
						margin-top: -24rpx;
						left: 0;
						width: 48rpx;
						height: 48rpx;
						background-repeat: no-repeat;
						background-position: center;
						background-size: 100%;
					}
					.alipay{
						background-image: url(../../static/images/order/ali-pay.png);
					}
					.wechatpay{
						background-image: url(../../static/images/order/wx-pay.png);
					}
					.name{
						line-height: 48rpx;
						font-size: 26rpx;
						color: #1A1A1A;
					}
					.select{
						position: absolute;
						top: 50%;
						margin-top: -20rpx;
						right: 0;
						width: 40rpx;
						height: 40rpx;
						background-repeat: no-repeat;
						background-position: center;
						background-size: 100%;
						background-image: url(../../static/images/cart/select.png);
					}
					.selected{
						background-image: url(../../static/images/cart/selected.png);
					}
				}
			}
		}
		.no-p-b{
			padding-bottom: 0;
		}
		.footer{
			box-sizing: border-box;
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			height: 100rpx;
			padding: 15rpx 36rpx;
			background-color: #FFFFFF;
			border-top: 1rpx solid #E4EAED;
			.btn{
				width: 100%;
				height: 70rpx;
				line-height: 70rpx;
				font-size: 26rpx;
				color: #FFFFFF;
				text-align: center;
				background-color: $color-common;
				border-radius: 35rpx;
			}
		}
	}
</style>
